package com.perfma.xtest.cmd;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 *
 * @author: junhui.si
 * @date: 2024-07-01 18:22
 **/
@Slf4j
public class M {
    public static final String XSHARK_LOG_HOME = "/Users/sijunhui/Downloads/log/xshark/logs/xshark";
    public static final String LIST_LOG_BY_TIME_SCRIPT = "/Users/sijunhui/Downloads/log/xshark/xshark/bin/list_log_by_time.sh";

    public static void main(String[] args) {
        ListLogByTimeTaskMsg msg = ListLogByTimeTaskMsg.builder()
                .id(1L)
                .startTime("2024-06-29 18:07")
                .engTime("2024-06-29 18:10")
                .build();
        listLogByTime(msg);
    }

    public static void listLogByTime(ListLogByTimeTaskMsg msg) {
        String id = String.valueOf(msg.getId());
        String startTimePrefix = msg.getStartTime().split(" ")[0];
        String endTimePrefix = msg.getEngTime().split(" ")[0];
        try {
            List<String> logFileList = Files.walk(Paths.get(XSHARK_LOG_HOME))
                    .filter(Files::isRegularFile)
                    .map(Path::getFileName)
                    .map(Path::toString)
                    .filter(s -> "common-default.log".equals(s) || "common-error.log".equals(s)
                            || (s.contains("common-") && (s.contains(startTimePrefix) || s.contains(endTimePrefix))))
                    .sorted()
                    .collect(Collectors.toList());
            if (logFileList.isEmpty()) {
                // 提示 todo sjh log
                return;
            }

            // 日志文件夹
            File newLogDirectory = new File(XSHARK_LOG_HOME, id);
            if (!newLogDirectory.exists()) {
                newLogDirectory.mkdirs();
            }
            String outputPath = XSHARK_LOG_HOME + "/" + id;
            for (String logFileName : logFileList) {
                String fileName = XSHARK_LOG_HOME + "/" + logFileName;
                String outputFile = outputPath + "/" + logFileName;
                listLogByTime(msg.getStartTime(), msg.getEngTime(), fileName, outputFile);
            }
        } catch (Exception e) {
            log.error("获取日志列表异常", e);
            // 错误 todo sjh log
        }
    }

    private static void listLogByTime(String startTime, String endTime, String fileName, String outputFileName) {
        String cmd = "sh " + LIST_LOG_BY_TIME_SCRIPT + " '" + startTime + "' '" + endTime + "' " + fileName + " " + outputFileName;
        ExecuteResult res = new OSExecutor().executeCommand(new String[]{"/bin/bash", "-c", cmd}, 10000);
        log.info("[ListLogByTimeHandler] cmd: {}, result: {}", cmd, res);
    }
}
